package d2_reflect_test;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * @Author:Cjj
 * @Date:2025/5/6
 * 反射Field
 */
public class Test3Field {
    @Test
    public void testGetField() throws NoSuchFieldException, IllegalAccessException {
        //1.反射第一步：必须先得到这个类的Class对象
        Class c = Cat.class;
        //2.获取类的全部成员变量
        Field[] fields = c.getFields();
        //3.遍历这个成员变量数组
        for (Field field : fields) {
            System.out.println(field.getName()+"---->"+field.getType());
        }
        //4.定位某个成员变量
        Field name = c.getDeclaredField("name");
        System.out.println(name.getName()+"---->"+name.getType());

        Field fAge = c.getDeclaredField("age");
        System.out.println(fAge.getName() + "---->" + fAge.getType());

       //赋值
         Cat cat = new Cat();
         name.setAccessible(true);//禁止访问控制权限
         name.set(cat,"小花猫");
         System.out.println(cat);

     //取值
        Object o = name.get(cat);
        System.out.println(o);
    }
}
